<?php

namespace App\Providers;

use App\Models\Common\Channel\Repositories\Interfaces\ChannelRepositoryInterface;
use App\Policies\Orders\OrderPolicy;
use App\Trip\Auth\JWT\Providers\LaravelServiceProvider;
use App\Trip\Auth\Providers\CacheModelUserProvider;
use App\Trip\Crypt\AppKey;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies
        = [
            // 'App\Models\Model' => 'App\Policies\ModelPolicy',
        ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();


        // 定义拦截器
        Gate::define('order-access', [OrderPolicy::class, 'access']);
        Gate::define('order-task-access', [OrderPolicy::class, 'access_task']);

        // 当前 channel
        $this->setCurrentChannel();
        $this->extendUserProvider();
        $jwt = new LaravelServiceProvider($this->app);
        $jwt->boot();
    }

    private function setCurrentChannel()
    {
        $app_key = request()->header('App-Key');
        $app_id  = $app_key ? AppKey::decrypt($app_key) : '';
        if ($app_id && AppKey::isAppValid($app_id)) {
            $channelRepo               = app(ChannelRepositoryInterface::class);
            $this->app['trip.channel'] = $channelRepo->findChannelByAppId($app_id);
        }

    }

    private function extendUserProvider()
    {
        //  cache model
        $this->app['auth']->provider(CacheModelUserProvider::class, function ($app, array $config) {
            return new CacheModelUserProvider($app['hash'], $config['model']);
        });
    }

    public function register()
    {
        $jwt = new LaravelServiceProvider($this->app);
        $jwt->register();
    }
}
